package com.ultrasoft.farmasoft.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ultrasoft.farmasoft.domain.User;

@Repository(value = "userDao")
@Transactional(readOnly = false)
public class UserDaoImpl implements UserDao {
	
	private EntityManager em = null;
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	} 
	
	@SuppressWarnings("unchecked")
	public List<User> getUserList() {
		return em.createNamedQuery("User.findAll").getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<User> getUserList(Integer rolId) {
		Query q = em.createNamedQuery("User.findByRolId");
    	q.setParameter("rolId",rolId);
    	return q.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getUserListExcept(Integer userId) {
		Query q = em.createNamedQuery("User.exceptByUserId");
    	q.setParameter("userId",userId);
    	return q.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getUserList(String login){
		Query q = em.createNamedQuery("User.findByLogin");
    	q.setParameter("login",login);
    	return q.getResultList();
	}
	
	public User findByUserId(Integer userId) {
		User res=null;
		try {
			res=em.find(User.class,userId);
		} catch (Exception e) {
			// TODO: handle exception
		}
    	return res;
	}
    public User findByLoginByPassword(String login, String password){
    	User res= null;
    	Query q = em.createNamedQuery("User.findByLoginByPassword");
    	q.setParameter("login",login);
    	q.setParameter("password",password);
    	if(q.getResultList().size() == 1 )
    		res=(User)q.getSingleResult();
    	return res;
    }
	public void update(User user) {
		em.merge(user);
	}
	public void remove(User user) {
		em.remove(em.getReference(User.class,user.getUserId()));
	}
	public void add(User user) {
		em.persist(user);
	}
}
